package com.ruoyi.subsidy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.NumCreateUtils;
import com.ruoyi.common.utils.uuid.NumCreateUtilsMachin;
import com.ruoyi.subsidy.domain.SysSubsidyApplication;
import com.ruoyi.subsidy.domain.bo.SysSubsidyApplicationBo;
import com.ruoyi.subsidy.domain.bo.SysSubsidyMachineBo;
import com.ruoyi.subsidy.domain.bo.SysSubsidyPlantingBo;
import com.ruoyi.subsidy.domain.bo.SysmachingBaseModelBo;
import com.ruoyi.subsidy.domain.vo.SysSubsidyApplicationVo;
import com.ruoyi.subsidy.mapper.SysSubsidyApplicationMapper;
import com.ruoyi.subsidy.mapper.SysSubsidyMachineMapper;
import com.ruoyi.subsidy.service.ISysSubsidyApplicationService;
import com.ruoyi.subsidy.service.ISysSubsidyMachineService;
import com.ruoyi.subsidy.service.ISysSubsidyMaterialService;
import com.ruoyi.system.domain.bo.SysSubsidyMaterialBo;
import com.ruoyi.system.domain.vo.SysSubsidyMaterialVo;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 补贴申请Service业务层处理
 *
 * @author nbacheng
 * @date 2025-08-07
 */
@RequiredArgsConstructor
@Service
public class SysSubsidyMachineServiceImpl implements ISysSubsidyMachineService {

    private final SysSubsidyMachineMapper baseMapper;

    private final ISysSubsidyMaterialService sysSubsidyMaterialService;

    private final ISysUserService userService;
    private final NumCreateUtilsMachin numCreateUtils;

    /**
     * 查询补贴申请
     */
    @Override
    public SysSubsidyMachineBo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询补贴申请列表
     */
    @Override
    public TableDataInfo<SysSubsidyMachineBo> queryPageList(SysSubsidyMachineBo bo, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        String key = loginUser.getRoles().get(0).getRoleKey();
        TableDataInfo<SysSubsidyMachineBo> table = new TableDataInfo<>();
        if( !"已完成".equals(bo.getStatus())) {
            if ("districtNongji".equals(key)) {
                bo.setNode(3);
                table = qureyBytotalMachineBoq(bo);
            }
            if ("townNongji".equals(key)) {
                if ("审核中".equals(bo.getStatusShow())) {
                    bo.setNode(3);
                }
                if ("待处理".equals(bo.getStatusShow())) {
                    bo.setNode(2);
                }
                if ("异常".equals(bo.getStatusShow())) {
                    bo.setNode(2);
                    bo.setStatus("异常");
                }
                if (StringUtils.isEmpty(bo.getStatusShow())) {
                    bo.setNode(23);
                    //  bo.setStatus("已处理");
                }
                table = qureyBytotalMachineBox(bo);
            }
            if ("common".equals(key)) {
                if ("待处理".equals(bo.getStatusShow())) {
                    bo.setNode(1);
                }
                if ("异常".equals(bo.getStatusShow())) {
                    bo.setStatus("异常");
                }
                if ("审核中".equals(bo.getStatusShow())) {
                    bo.setNode(23);
                }
                table = qureyBytotalMachineBoc(bo);
                //bo.setNodeName(boo.getTownName());
            }
        }
        LambdaQueryWrapper<SysSubsidyMachineBo> lqw = buildQueryWrapper(bo);
        Page<SysSubsidyMachineBo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<SysSubsidyMachineBo> list = result.getRecords();
        list.forEach(e -> {
            if (StringUtils.isEmpty(bo.getStatusShow())) {
                if ("common".equals(key)) {
                    if ("异常".equals(e.getStatus())) {
                        e.setStatusShow("异常");
                    } else {
                        if ("1".equals(String.valueOf(e.getNode()))) {
                            e.setStatusShow("待处理");
                        } else {
                            e.setStatusShow("审核中");
                        }
                    }
                }
                if ("townNongji".equals(key)) {
                    if ("异常".equals(e.getStatus())) {
                        e.setStatusShow("异常");
                    } else {
                        if ("2".equals(String.valueOf(e.getNode()))) {
                            e.setStatusShow("待处理");
                        } else {
                            e.setStatusShow("审核中");
                        }
                    }
                }
                if ("districtNongji".equals(key)) {
                    e.setStatusShow("待处理");
                }
            } else {
                e.setStatusShow(bo.getStatusShow());
            }
        });
        TableDataInfo<SysSubsidyMachineBo> tableNew = table.build(result);
        tableNew.setShenhetotal(null == table ? 0 : table.getShenhetotal());
        tableNew.setDaichutotal(null == table ? 0 : table.getDaichutotal());
        tableNew.setYichangtotal(null == table ? 0 : table.getYichangtotal());
        return tableNew;
    }


    @Override
    public TableDataInfo<SysSubsidyMachineBo> qureyBytotalMachineBoc(SysSubsidyMachineBo bo) {
        LambdaQueryWrapper<SysSubsidyMachineBo> lqw = buildQueryWrapper(bo);

        //Page<SysSubsidyMachineBo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        // List<SysSubsidyMachineBo> list=result.getRecords();
        //  list.forEach(e->{
        //  });
        return baseMapper.qureyBytotalMachineBoc(bo);
    }

    @Override
    public TableDataInfo<SysSubsidyMachineBo> qureyBytotalMachineBox(SysSubsidyMachineBo bo) {
        LambdaQueryWrapper<SysSubsidyMachineBo> lqw = buildQueryWrapper(bo);
        return baseMapper.qureyBytotalMachineBox(bo);
    }

    @Override
    public TableDataInfo<SysSubsidyMachineBo> qureyBytotalMachineBoq(SysSubsidyMachineBo bo) {
        LambdaQueryWrapper<SysSubsidyMachineBo> lqw = buildQueryWrapper(bo);
        return baseMapper.qureyBytotalMachineBoq(bo);
    }

    /**
     * 查询补贴申请列表
     */
    @Override
    public List<SysSubsidyMachineBo> queryList(SysSubsidyMachineBo bo) {
        LambdaQueryWrapper<SysSubsidyMachineBo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询补贴申请列表
     */
    @Override
    public List<String> listMachingModel(SysSubsidyMachineBo bo) {
        //LambdaQueryWrapper<SysSubsidyMachineBo> lqw = buildQueryWrapper(bo);
        return baseMapper.listMachingModel(bo);
    }

    /**
     * 查询补贴申请列表
     */
    @Override
    public List<SysmachingBaseModelBo> listMachingByName(SysSubsidyMachineBo bo) {
        //LambdaQueryWrapper<SysSubsidyMachineBo> lqw = buildQueryWrapper(bo);
        return baseMapper.listMachingByName(bo);
    }

    private LambdaQueryWrapper<SysSubsidyMachineBo> buildQueryWrapper(SysSubsidyMachineBo bo)  {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysSubsidyMachineBo> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getAppType()), SysSubsidyMachineBo::getAppType, bo.getAppType());
        lqw.eq(StringUtils.isNotBlank(bo.getAppNum()), SysSubsidyMachineBo::getAppNum, bo.getAppNum());
        lqw.eq(StringUtils.isNotBlank(bo.getAppyBy()), SysSubsidyMachineBo::getAppyBy, bo.getAppyBy());
        lqw.eq(StringUtils.isNotBlank(bo.getIdCard()), SysSubsidyMachineBo::getIdCard, bo.getIdCard());
        lqw.eq(StringUtils.isNotBlank(bo.getBankCard()), SysSubsidyMachineBo::getBankCard, bo.getBankCard());
        lqw.eq(StringUtils.isNotBlank(bo.getVillageName()), SysSubsidyMachineBo::getVillageName, bo.getVillageName());
        lqw.eq(StringUtils.isNotBlank(bo.getTownName()), SysSubsidyMachineBo::getTownName, bo.getTownName());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysSubsidyMachineBo::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getYear()), SysSubsidyMachineBo::getYear, bo.getYear());
        if ("23".equals(String.valueOf(bo.getNode()))) {
            lqw.in(bo.getNode() != null, SysSubsidyMachineBo::getNode, Arrays.asList(2, 3));
        } else {
            lqw.eq(bo.getNode() != null, SysSubsidyMachineBo::getNode, bo.getNode());
        }
        lqw.eq(StringUtils.isNotBlank(bo.getSubmitBy()), SysSubsidyMachineBo::getSubmitBy, bo.getSubmitBy());
        // lqw.eq(bo.getSubmitDate() != null, SysSubsidyMachineBo::getSubmitDate, bo.getSubmitDate());
        /*if (bo.getStartDate() != null && bo.getEndDate() != null) {
            lqw.between(SysSubsidyMachineBo::getSubmitDate,
                bo.getStartDate(),
                bo.getEndDate());
        }*/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = null;
        Date endDate = null;
        if (bo.getStartDate() != null && !bo.getStartDate().isEmpty()) {
            try {
                startDate = sdf.parse(bo.getStartDate());
            } catch (ParseException e) {
                throw new RuntimeException("时间格式不对");
            }
        }
        if (bo.getEndDate() != null && !bo.getEndDate().isEmpty()) {
            try {
                endDate = sdf.parse(bo.getEndDate());
            } catch (ParseException e) {
                throw new RuntimeException("时间格式不对");
            }
        }
        if (startDate != null && endDate != null) {
            lqw.ge(SysSubsidyMachineBo::getSubmitDate, startDate).lt(SysSubsidyMachineBo::getSubmitDate, new Date(endDate.getTime() + 24 * 60 * 60 * 1000 - 1));
        }
        // 新增排序条件（降序）
        lqw.orderByDesc(SysSubsidyMachineBo::getSubmitDate);
        return lqw;
    }

    /**
     * 新增补贴申请
     */
    @Override
    public String insertByBo(SysSubsidyMachineBo bo) {
        //SysSubsidyMachineBo add = BeanUtil.toBean(bo, SysSubsidyMachineBo.class);
        validEntityBeforeSave(bo);
        String num = numCreateUtils.generateOrderNumber();
        bo.setAppNum(num);
        if (bo.getListMateria() != null) {
            List<SysSubsidyMaterialBo> listMateria = bo.getListMateria();
            listMateria.forEach(e -> {
                e.setAppNum(num);
                sysSubsidyMaterialService.insertByBo(e);
            });
        }
        LoginUser loginUser = LoginHelper.getLoginUser();
        String key = loginUser.getRoles().get(0).getRoleKey();
        if ("common".equals(key)) {
            bo.setNode(2);
            bo.setSubmitNode("1");
            bo.setStatus("审核中");
            bo.setNodeName(loginUser.getTownName());
        }
        if ("townNongji".equals(key)) {
            bo.setNode(3);
            bo.setSubmitNode("2");
            bo.setStatus("审核中");
            bo.setNodeName("滴道区");
        }
        // loginUser.getRolePermission().
        //  if (bo.getSubmitBy().contains())
        boolean flag = baseMapper.insertSubsidyMachine(bo) > 0;
        //if (flag) {
        //   bo.setId(add.getId());
        return num;
    }

    /**
     * 修改补贴申请
     */
    @Override
    public Boolean updateByBo(SysSubsidyMachineBo bo) {
        SysSubsidyMachineBo update = BeanUtil.toBean(bo, SysSubsidyMachineBo.class);
        //validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean updateByMachineBo(SysSubsidyMachineBo bo) {
        SysSubsidyMachineBo update = BeanUtil.toBean(bo, SysSubsidyMachineBo.class);
        //validEntityBeforeSave(update);
        return baseMapper.updateByMachineBo(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysSubsidyMachineBo entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除补贴申请
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
